import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbfdsys } from '../../../atoms/db';

const logger = anylogger('pages/api/introduction/publish/content.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	content: string;
};


/**
 * pages/api/introduction/publish/content.增加简介内容
 */
const handler = an48<Result>();

const key = 'desc';

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { content } = req.body as Message;
		if (typeof content !== 'string') {
			res.status(200).json({
				ok: false,
				message: '缺少必要参数'
			});
			return;
		}
		const r = await tbfdsys().first('*').where({
			key
		});

		if (r) {	// update
			await tbfdsys().where({
				key

			})
				.update({
					value: content
				});
			res.status(200).json({ ok: true });
			return;
		}
		// insert new record
		await tbfdsys().insert({
			key,
			value: content
		});
		res.status(200).json({
			ok: true,
		});
	} catch (error) {
		logger.trace(error);
		res.status(200).json({
			ok: false,
			message: (error as Error).message
		});
	}
});

export const config = {} as PageConfig;

export default handler;
